'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import BrandCard from '@/components/BrandCard';

interface Brand {
  brand: string;
  name: string;
  alphabet: string;
  country: string;
  hot: string;
  desc: string;
  story: string;
}

export default function BrandsPage() {
  const [brands, setBrands] = useState<Brand[]>([]);
  const [filteredBrands, setFilteredBrands] = useState<Brand[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCountry, setSelectedCountry] = useState('all');
  const [selectedHot, setSelectedHot] = useState('all');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadBrands = async () => {
      try {
        // 动态导入brandData.js
        const brandData = await import('@/../public/brandData.js');
        setBrands(brandData.default);
        setFilteredBrands(brandData.default);
      } catch (error) {
        console.error('加载品牌数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadBrands();
  }, []);

  useEffect(() => {
    let filtered = brands;

    // 搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(brand => 
        brand.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        brand.brand.toLowerCase().includes(searchTerm.toLowerCase()) ||
        brand.country.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 国家过滤
    if (selectedCountry !== 'all') {
      filtered = filtered.filter(brand => brand.country === selectedCountry);
    }

    // 热门过滤
    if (selectedHot !== 'all') {
      filtered = filtered.filter(brand => brand.hot === selectedHot);
    }

    setFilteredBrands(filtered);
  }, [brands, searchTerm, selectedCountry, selectedHot]);

  const countries = [...new Set(brands.map(brand => brand.country))];
  const totalCars = brands.reduce((sum, brand) => sum + 8, 0); // 假设每个品牌有8款车型

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="container mx-auto px-4">
          <div className="text-center">
            <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">加载品牌数据中...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        {/* Page Header */}
        <div className="text-center mb-12">
          <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">汽车品牌</h1>
          <p className="text-xl text-gray-600 max-w-2xl mx-auto">
            探索世界顶级汽车品牌，每个品牌都有其独特的历史、文化和技术特色
          </p>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-lg shadow-md p-6 text-center hover:shadow-lg transition-shadow">
            <div className="text-3xl font-bold text-blue-600 mb-2">{brands.length}</div>
            <div className="text-gray-600">合作品牌</div>
          </div>
          <div className="bg-white rounded-lg shadow-md p-6 text-center hover:shadow-lg transition-shadow">
            <div className="text-3xl font-bold text-green-600 mb-2">{totalCars}</div>
            <div className="text-gray-600">在售车型</div>
          </div>
          <div className="bg-white rounded-lg shadow-md p-6 text-center hover:shadow-lg transition-shadow">
            <div className="text-3xl font-bold text-purple-600 mb-2">{countries.length}</div>
            <div className="text-gray-600">覆盖国家</div>
          </div>
          <div className="bg-white rounded-lg shadow-md p-6 text-center hover:shadow-lg transition-shadow">
            <div className="text-3xl font-bold text-orange-600 mb-2">
              {Math.max(...brands.map(b => 2024 - parseInt(b.story.match(/\d{4}/)?.[0] || '2000')))}
            </div>
            <div className="text-gray-600">最长历史</div>
          </div>
        </div>

        {/* Filters */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-8">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {/* 搜索框 */}
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">搜索品牌</label>
              <input
                type="text"
                placeholder="输入品牌名称或国家..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            {/* 国家筛选 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">国家/地区</label>
              <select
                value={selectedCountry}
                onChange={(e) => setSelectedCountry(e.target.value)}
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">全部国家</option>
                {countries.map(country => (
                  <option key={country} value={country}>{country}</option>
                ))}
              </select>
            </div>

            {/* 热门筛选 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">热门品牌</label>
              <select
                value={selectedHot}
                onChange={(e) => setSelectedHot(e.target.value)}
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">全部品牌</option>
                <option value="1">热门品牌</option>
                <option value="0">其他品牌</option>
              </select>
            </div>
          </div>
        </div>

        {/* Results Info */}
        <div className="flex justify-between items-center mb-6">
          <div className="text-gray-600">
            找到 {filteredBrands.length} 个品牌
            {searchTerm && ` (搜索: "${searchTerm}")`}
          </div>
          <div className="flex space-x-2">
            <button className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 text-sm">
              按名称排序
            </button>
            <button className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 text-sm">
              按热度排序
            </button>
          </div>
        </div>

        {/* Brands Grid */}
        {filteredBrands.length === 0 ? (
          <div className="text-center py-16">
            <div className="text-6xl mb-4">🔍</div>
            <h3 className="text-xl font-semibold text-gray-900 mb-2">未找到匹配的品牌</h3>
            <p className="text-gray-600">请尝试调整搜索条件或筛选器</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {filteredBrands.map((brand, index) => (
              <BrandCard key={brand.brand} brand={brand} showDetails={true} />
            ))}
          </div>
        )}

        {/* CTA Section */}
        <div className="bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl p-8 mt-16 text-center text-white">
          <h2 className="text-2xl md:text-3xl font-bold mb-4">找不到您喜欢的品牌？</h2>
          <p className="text-lg mb-6 text-blue-100">
            我们与全球众多汽车品牌保持合作关系，如果您有特殊需求，请联系我们
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Link
              href="/contact"
              className="bg-white text-blue-600 hover:bg-gray-100 px-6 py-3 rounded-lg font-semibold transition-colors"
            >
              联系我们
            </Link>
            <Link
              href="/cars"
              className="bg-transparent border-2 border-white hover:bg-white hover:text-blue-600 px-6 py-3 rounded-lg font-semibold transition-colors"
            >
              浏览所有车辆
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}